<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表卡片区 -->
    <el-card class="box-card">
      <!-- 2.搜索区域 -->
      <el-page-header style="margin-bottom: 2vh" @back="goBack" :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
      <el-form :inline="true" ref="form"  label-width="120px" size="small">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item>
        </el-form-item>
        <el-form-item>
          <el-input
              @keyup.enter.native="searchUser"
              @clear="searchUser"
              style="width: 150px"
              clearable
              v-model="queryMap.empName"
              placeholder="请输入登录名查询"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              @keyup.enter.native="searchUser"
              clearable
              @clear="searchUser"
              style="width: 170px"
              v-model="queryMap.phone"
              placeholder="请输入电话查询"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input clearable @clear="searchUser"   style="width: 150px" v-model="queryMap.nickName" placeholder="请输入昵称查询"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select
              clearable
              v-model="queryMap.status"
              @clear="searchUser"
              style="width: 150px"
              placeholder="请选择用户状态"
          >
            <!--                    状态 0：未开启外呼，1：已开启外呼，-1：冻结-->
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="0"></el-option>
            <el-option label="冻结" value="-1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left:1vh">
          <el-button  @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" @click="searchUser" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button :disabled="multipleSelection.length === 0" v-has-permission="'emp:dongjie'" @click="updateStatusMore(-1)">批量冻结</el-button>
        <el-button :disabled="multipleSelection.length === 0" v-has-permission="'emp:dongjie'" @click="updateStatusMore(0)">批量解冻</el-button>
        <el-button
            icon="el-icon-plus"
            @click="addDialogVisible=true"
            v-hasPermission="'emp:add'"
        >添加</el-button>
        <el-button @click="downExcel" v-hasPermission="'emp:export'"  icon="el-icon-download">导出</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table ref="multipleTable"  @selection-change="handleSelectionChange" v-loading="loading" size="small" :data="userList" border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="empName" label="用户名" width="100"></el-table-column>
        <el-table-column prop="nickName" label="昵称" width="100"></el-table-column>
        <el-table-column
            label="角色名"
            width="100">
          <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.roleName }}</el-tag>
              </div>
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" width="100" sortable></el-table-column>
        <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
        <el-table-column prop="phone" label="手机" width="150"></el-table-column>
        <el-table-column prop="createTime" label="入职时间" width="150"></el-table-column>
        <!--                <el-table-column prop="status" label="是否禁用" width="100">-->
        <!--                    <template v-slot="scope">-->
        <!--                        <el-switch v-model="scope.row.status" @change="changUserStatus(scope.row)"></el-switch>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <el-table-column prop="status" label="状态" width="80">
          <template v-slot="scope">
            <el-span v-if="scope.row.status==0 || scope.row.status==1"  type="success" size="small">正常</el-span>
            <el-span v-if="scope.row.status==-1"  type="danger" size="small">冻结</el-span>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template v-slot="scope">
            <el-tooltip content="编辑" placement="top" effect="light">

              <el-button  circle round plain v-hasPermission="'emp:edit'" size="small" type="primary" icon="el-icon-edit-outline" @click="edit(scope.row.empId)"></el-button>
              <!--                        <el-button v-hasPermission="'user:delete'" type="danger" size="small" icon="el-icon-delete" @click="del(scope.row.userId)"></el-button>-->
            </el-tooltip>

            <el-tooltip content="下线" placement="top" effect="light">

              <el-button circle round plain icon="el-icon-warning-outline"  v-hasPermission="'emp:delete'" type="danger" size="small" @click="updateStatus(scope.row.empId,-2)"></el-button>
            </el-tooltip>

            <el-tooltip content="冻结" placement="top" effect="light">
              <el-button  v-has-permission="'emp:dongjie'" circle round plain icon="el-icon-turn-off" v-if="scope.row.status==0 || scope.row.status==1" v-hasPermission="'user:delete'" type="warning" size="small" @click="updateStatus(scope.row.empId,-1)"></el-button>
            </el-tooltip>

            <el-tooltip content="解冻" placement="top" effect="light">
              <el-button v-has-permission="'emp:dongjie'" circle round plain icon="el-icon-open" v-if="scope.row.status==-1" v-hasPermission="'user:delete'" type="success" size="small" @click="updateStatus(scope.row.empId,0)"></el-button>
            </el-tooltip>

            <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
            >
              <el-button
                  circle round plain
                  v-has-permission="'emp:assign'"
                  type="warning"
                  size="small"
                  icon="el-icon-s-tools"
                  @click="assignRoles(scope.row.empId)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="[6, 10, 20, 30]"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

      <!-- 添加对话框 -->
      <el-dialog title="添加员工" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
        <!-- 表单 -->
        <span>
          <el-form
              :model="addForm"
              :label-position="labelPosition"
              :rules="addFormRules"
              ref="addFormRef"
              label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="登录名" prop="empName">
                    <el-input v-model="addForm.empName"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="deptId">
                    <el-select v-model="addForm.deptId" placeholder="请选择所属部门">
                      <el-option
                          v-for="department in departments"
                          :key="department.deptId"
                          :label="department.deptName"
                          :value="department.deptId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="addForm.nickName"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="1">
               <span style="font-size: 0;" >1</span>
              </el-col>
              <el-col :span="13">
<!--               <span style="margin-right: 2vh">是否为超级管理员</span>-->
                <el-form-item label="是否为超级管理员" label-width="130px">
                   <el-radio v-model="addForm.type" style="margin-left: 1vh" label="1">否</el-radio>
                   <el-radio v-model="addForm.type" label="0">是</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="phone">
              <el-input v-model="addForm.phone"></el-input>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="addUser"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
        <span>
          <el-form
              :model="editForm"
              :label-position="labelPosition"
              :rules="addFormRules"
              ref="editFormRef"
              label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="登录名" prop="empName">
                    <el-input v-model="editForm.empName" :disabled="true"></el-input>
                    <el-input
                        type="hidden"
                        v-model="editForm.empId"
                        :disabled="true"
                        style="display:none;"
                    ></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="deptId">
                    <el-select v-model="editForm.deptId" placeholder="请选择所属部门">
                      <el-option
                          v-for="department in departments"
                          :key="department.deptId"
                          :label="department.deptName"
                          :value="department.deptId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="editForm.nickName"></el-input>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="editForm.phone"></el-input>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
              type="primary"
              @click="updateUser"
              :loading="btnLoading"
              :disabled="btnDisabled"
          >确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog center title="分配角色" :visible.sync="assignDialogVisible" width="30%">
              <span>
                <template>
<!--                  <el-transfer-->
                  <!--                          filterable-->
                  <!--                          :titles="['未拥有','已拥有']"-->
                  <!--                          :button-texts="['到左边', '到右边']"-->
                  <!--                          v-model="value"-->
                  <!--                          :data="roles"-->
                  <!--                  ></el-transfer>-->
                  <el-radio-group v-model="valueRole" v-for="(roleI,index) in roles" :key="roleI.key">
                    <el-radio style="margin: 1vh"  :label="roleI.key">{{roleI.label}}</el-radio>
                  </el-radio-group>
                </template>
              </span>
        <span slot="footer" class="dialog-footer">
<!--                <el-button @click="assignDialogVisible = false" class="el-icon-close">取消分配</el-button>-->
                <el-button
                    v-hasPermission="'user:assign'"
                    type="primary"
                    @click="doAssignRoles"
                    class="el-icon-check"
                    :disabled="btnDisabled"
                >确定分配</el-button>
              </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    return {
      btnLoading: false,
      btnDisabled: false,
      departments: [],
      loading: true,
      total: 0,
      addDialogVisible: false, //添加对话框,
      editDialogVisible: false, //修改对话框
      assignDialogVisible: false, //分配角色对话框
      labelPosition: "right", //lable对齐方式
      multipleSelection:[],
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 6,
        empName: "",
        deptId:"",
        nickName: "",
        phone:"",
        type:'1'
      },
      userList: [],

      addForm: {
        userName: "",
        nickName: "",
        password: "",
        email: "",
        phone: "",
        deptId: "",
        type:'1'
      }, //添加表单
      editForm: {}, //更新表单
      addFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12 个字符", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "请选择部门", trigger: "blur" }
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        birth: [{ required: true, message: "请填写出生日期", trigger: "blur" }],
        email: [{ required: true, validator: checkEmail, trigger: "blur" }],
        phone: [
          {
            required: true,
            message: "请输入联系方式",
            validator: checkPhone,
            trigger: "blur"
          }
        ],
        nickName: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { min: 5, max: 10, message: "长度在 5 到 10 个字符", trigger: "blur" }
        ]
      }, //添加表单验证规则
      roles: [], //角色
      value: [], //用户拥有的角色
      valueRole: '', //用户拥有的角色
      uid: ""
    };
  },
  methods: {

    /**
     * 全选功能
     *
     */

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    //多选删除   只能改为 -2进入离职分配中

    async updateStatusMore(status){
      let desc = '';
      if(status===0){
        desc='解冻';
      }else if(status===-1){
        desc='冻结';
      }
      const ids = this.multipleSelection.map(row => row.userId); // 提取出所有选中行的ID
      const res = await this.$confirm(
          "确定"+desc+"选中的用户？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消"
        });
      });
      if (res === "confirm") {
        const { data: res } = await this.$http.post("system/user/delmore/"+status+"/",{ids});
        console.log(res);
        if(res.success){
          this.$notify.success({
            title:'操作成功',
            message:desc+'成功',
          });
          await this.getUserList();
        }else {
          this.$message.error(res.data.errorMsg);
        }
      }
    },




    /**
     * 重置
     */
    reset(){
      this.queryMap= {
        pageNum: 1,
        pageSize: 6,
        userName: "",
        sex: "",
        deptId: "",
        nickName: ""
      };
    },
    /**
     * 加载用户表格
     */
    downExcel() {
      const $this = this;
      const res = axios
          .request({
            url: "http://47.99.186.44:8990/system/user/excel",
            method: "post",
            responseType: "blob",
            headers:{'Authorization':LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},	//设置请求头
          })
          .then(res => {
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [user:export]"
              );
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "用户列表.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          });
    },
    /**
     * 弹出用户分配角色
     */
    async assignRoles(id) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      const { data: res } = await this.$http.get("system/user/" + id + "/roles");
      if (res.success) {
        this.roles = res.data.roles;
        this.valueRole = res.data.valueRole;
        this.uid = id;
        setTimeout(() => {
          loading.close();
          this.assignDialogVisible = true;
        }, 400);
      } else {
        this.$message.error("分配角色失败:" + res.data.errorMsg);
      }
    },
    /**
     * 确定分配角色
     */
    async doAssignRoles() {
      this.assignDialogVisible = true;
      this.btnDisabled = true;
      const { data: res } = await this.$http.post(
          "system/user/" + this.uid + "/assignRoles",
          this.valueRole
      );
      if(res.success){
        this.assignDialogVisible = false;
        this.btnDisabled = false;
        this.$notify.success({
          title:'操作成功',
          message:'用户分配角色成功',
        });
        await this.getUserList();
        // await this.getDepartmets();

      } else {
        this.$message.error("分配角色失败:" + res.data.errorMsg);
      }

    },
    /**
     * 加载用户列表
     */
    async getUserList() {
      const { data: res } = await this.$http.get("system/user/findUserList", {
        params: this.queryMap
      });
      if(!res.success){
        return this.$message.error("获取用户列表失败:"+res.data.errorMsg);
      }
      this.total = res.data.total;
      this.userList = res.data.rows;
      console.log(this.userList)
    },

    /**
     * 冻结-1   下线：-2
     */
    async updateStatus(id,status) {
      let desc = '';
      if(status===-1){
        desc='冻结';
      }else if(status===-2){
        desc='下线';
      }
      const res = await this.$confirm(
          "确定要"+desc+"用户吗?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消操作"
        });
      });
      if (res === "confirm") {
        const { data: res } = await this.$http.delete("system/user/delete/" + id+ "/"+status);
        console.log(res);
        if(res.success){
          this.$notify.success({
            title:'操作成功',
            message:'用户状态更新成功',
          });
          await this.getUserList();
          await this.getDepartmets();
        }else {
          this.$message.error(res.data.errorMsg);
        }
      }
    },
    /**
     * 添加用户
     */
    async addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          this.btnLoading = true;
          this.btnDisabled = true;
          const { data: res } = await this.$http.post("system/user/add", this.addForm);
          if(res.success){
            this.$notify.success({
              title:'操作成功',
              message:'用户添加成功',
            });
            this.addForm = {};
            await this.getUserList();
            await this.getDepartmets();
          } else {
            return this.$message.error("用户添加失败:" + res.data.errorMsg);
          }
          this.addDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    /**
     * 更新用户
     */
    async updateUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          this.btnLoading = true;
          this.btnDisabled = true;
          console.log(this.editForm)
          const { data: res } = await this.$http.put(
              "system/user/update/" + this.editForm.empId,
              this.editForm
          );
          if(res.success){
            this.$notify({
              title: "操作成功",
              message: "用户基本信息已更新",
              type: "success"
            });
            this.editForm = {};
            await this.getUserList();
            await this.getDepartmets();
          } else {
            this.$message.error("用户信息更新失败:" + res.data.errorMsg);
          }
          this.editDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    /**
     * 搜索用户
     */
    searchUser() {
      this.queryMap.pageNum = 1;
      this.getUserList();
    },
    /**
     * 修改用户信息
     */
    async edit(id) {
      const { data: res } = await this.$http.get("system/user/edit/" + id);
      if(res.success){
        this.editForm = res.data;
        this.editDialogVisible = true;
      } else {
        return this.$message.error("用户信息编辑失败:" + res.data.errorMsg);
      }
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getUserList();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getUserList();
    },

    /**
     * 关闭添加弹出框
     */
    closeDialog() {
      this.$refs.addFormRef.clearValidate();
      this.addForm.birth = "";
      this.addForm = {};
    },
    /**
     * 关闭编辑弹出框
     */
    editClose() {
      this.$refs.editFormRef.clearValidate();
      this.editForm = {};
    },
    /**
     * 禁用启用用户
     */
    async changUserStatus(row) {
      const { data: res } = await this.$http.put(
          "system/user/updateStatus/" + row.id + "/" + row.status
      );
      if(!res.success){
        this.$message.error("更新用户状态失败:" + res.data.errorMsg);
        row.status = !row.status;
      } else {
        const message = row.status ? '用户状态已禁用' : '用户状态已启用';
        this.$notify.success({
          title: '操作成功',
          message: message,
        });
      }
    },
    /**
     * 加载所有部门
     */
    async getDepartmets() {
      const { data: res } = await this.$http.get("system/dept_emp/findAll");
      if(!res.success){
        return this.$message.error("获取部门列表失败:"+res.data.errorMsg);
      }
      //this.data = res.data.tree;
      this.departments = res.data;
    },
  },
  created() {
    this.getUserList();
    this.getDepartmets();
    setTimeout(() => {
      this.loading = false;
    }, 500);
  }
};
</script>
